//
//  NumberVC.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/19/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class NumberViewController: UIViewController, Alertable {
    
    // MARK: - Outlets
    
    lazy private var spinner = SpinnerView()

     private lazy var submitBtn: UIButton = {
        let btn = UIButton()
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 15
        btn.setTitle("Продолжить", for: .normal)
        btn.backgroundColor = .blueColor
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel!.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        return btn
    }()

    private lazy var tableView: UITableView = {
        let table = UITableView()
        table.delegate = self
        table.dataSource = self
        
        table.register(NumberCell.self, forCellReuseIdentifier: "NumberCell")
        table.register(NumberOptionsCell.self, forCellReuseIdentifier: "NumberOptionsCell")

        table.tableFooterView = UIView ()
        table.separatorStyle = .none
        table.showsVerticalScrollIndicator = false
        return table
    }()

    // MARK: - Props
    
    private var numberViewModel = NumberViewModel()
    public weak var delegate: AdCreatorProtocol!
    
    private var selectedNumber: Int? {
        didSet {
            if selectedNumber != nil {
                self.submitBtn.isEnabled = true
                self.submitBtn.alpha = 1
            } else {
                self.submitBtn.isEnabled = false
                self.submitBtn.alpha = 0.6
            }
        }
    }
    
    private var lastRow: Int?
    private var nextPage: String?
    private var isLoading: Bool = true {
        didSet {
            isLoading ? spinner.startAnimating() : spinner.stopAnimating()
            view.isUserInteractionEnabled = !isLoading
        }
    }
    
    // MARK: - UI Actions
    
    @objc private func goBack(sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    @objc private func closeVC(sender: UIBarButtonItem) {
        self.navigationController?.dismiss(animated: true, completion: nil)
        delegate.removeEverything()
    }
    
    // TODO: May be we have to just fetch one more time
    
    @objc private func getNumber (notification: NSNotification) {
        if let userInfo = notification.userInfo {
            let data = userInfo["data"] as! NumberViewModel.Number
            self.numberViewModel.myNumbers.append(data)
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name("sendNumber"), object: nil)
            self.tableView.reloadData()
        }
    }
    
    @objc private func addNumber (sender: UIButton) {
        let vc = VerifyNumberVC()
        self.navigationController?.pushViewController(vc, animated: true)
        NotificationCenter.default.addObserver(self, selector: #selector(getNumber(notification:)), name: NSNotification.Name("sendNumber"), object: nil)
    }
    
    @objc private func onReadyClick (sender: UIButton) {
        
        let number = self.numberViewModel.myNumbers.first(where: {
            $0.id == self.selectedNumber
        })
        
        delegate.getPhoneNumber(number: number, onlyChat: false, noReseller: false, isProtected: false)
        let contactsVC = ContactsViewController()
        contactsVC.delegate = self.delegate
        self.navigationController?.pushViewController(contactsVC, animated: true)
    }
    
    // MARK: - Life-Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUpUI()
        self.setUpNavBar()
    }

    override func viewWillAppear(_ animated: Bool) {
        self.loadNumbers()
    }
    
}


// MARK: - Methods

extension NumberViewController {
    private func loadNumbers () {
        self.isLoading = true
        
        let isNewPage = nextPage == nil || nextPage!.isEmpty
        
        let request = !isNewPage ? URLRequest(url: URL(string: nextPage!)!) : URLRequest(url: Request(base: .advert).getUrl(path:"users/phones/"))
        numberViewModel.loadNumbers(request: request) { (result) in
            self.isLoading = false
            switch result {
            case .failure(let error):
                self.alertError(error: error)
            case .success(let response):
                if isNewPage {
                    self.numberViewModel.myNumbers = response.results
                } else {
                    self.numberViewModel.myNumbers.append(contentsOf: response.results)
                }
                self.nextPage = response.next
                self.tableView.reloadData()
            }
        }
    }
}

// MARK: - Table View

extension NumberViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? self.numberViewModel.myNumbers.count : 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "NumberCell") as! NumberCell
        cell.number = self.numberViewModel.myNumbers[indexPath.row]
        cell.parent = self
        cell.selectedChexBox = selectedNumber
        cell.selectionStyle = .none
        return cell

        
        // TODO: Under Phone Cell
//        let cell = tableView.dequeueReusableCell(withIdentifier: "NumberOptionsCell") as! NumberOptionsCell
//        cell.selectionStyle = .none
//        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            let view = UIView()
            
            let label = UILabel()
            label.font = UIFont.systemFont(ofSize: 15, weight: .regular)
            label.textColor = .blueColor
            label.textAlignment = .left
            label.text = "Добавить номер"
            
            let icon = UIImageView()
            icon.image = UIImage(named: "plus")
            icon.contentMode = .scaleAspectFit

            view.addSubview(label)
            view.addSubview(icon)
            
            label.snp.makeConstraints { (make) in
                make.leading.centerY.equalToSuperview()
            }
            icon.snp.makeConstraints { (make) in
                make.trailing.centerY.equalToSuperview()
                make.width.height.equalTo(16)
            }
            
            let gesture = UITapGestureRecognizer(target: self, action: #selector(addNumber(sender:)))
            view.addGestureRecognizer(gesture)
            
            return view
        } else {
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return section == 0 ? 60 : 0
    }
    
}

// MARK: - UI

extension NumberViewController {
    
    private func setUpUI () {
        view.backgroundColor = .white
        self.view.addSubview(submitBtn)
        self.view.addSubview(tableView)
        self.view.addSubview(spinner)
        
        submitBtn.addTarget(self, action: #selector(onReadyClick(sender:)), for: .touchUpInside)
        
        self.addConstraints()
        selectedNumber = nil
        self.addCloseIcon()
    }
    
    private func addConstraints () {
        submitBtn.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-16)
            make.height.equalTo(44)
        }
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(view.safeAreaLayoutGuide).offset(30)
            make.bottom.equalTo(submitBtn.snp.top).offset(-12)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        spinner.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    private func setUpNavBar () {
        let backIcon = UIImage(named: "cancel")
        let backButton = UIBarButtonItem(image: backIcon, landscapeImagePhone: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .greyColor
        
        self.navigationItem.simpleNavBar(title: "Номер телефона", backButton: backButton)
        navigationItem.largeTitleDisplayMode = .always
        navigationController?.navigationBar.largeTitleTextAttributes = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24, weight: .bold)
        ]
        navigationItem.hidesSearchBarWhenScrolling = false
        self.navigationController?.navigationItem.largeTitleDisplayMode = .always
    }
    
    private func addCloseIcon () {
        let closeBarBnt = UIBarButtonItem(image: UIImage(named: "dismiss"), style: .plain, target: self, action: #selector(closeVC))
        closeBarBnt.tintColor = .greyColor
        self.navigationItem.rightBarButtonItem = closeBarBnt
    }

    private func alertError (error: RequestError) {
        switch error {
            case .general:
                self.showAlert("Упс...", "Неизвестная ошибка")
            case .parameter(let message):
               self.showAlert("Упс...", message)
        }
    }
}


extension NumberViewController: ModalElementProtocol {
    
    func selectElement(modal: ModalView.ModalType?, customID: Int?) {
        selectedNumber = customID
        
        if lastRow != nil {
            tableView.reloadRows(at: [IndexPath(item: lastRow!, section: 0)], with: .bottom)
        }
        
        lastRow = self.numberViewModel.myNumbers.firstIndex(where: {
            $0.id == customID
        })
        
        tableView.reloadRows(at: [IndexPath(row: lastRow!, section: 0)], with: .top)
    }
    
    func didClear(modal: ModalView.ModalType) { }
}


